package com.qf.student.web;

import com.alibaba.fastjson.JSON;
import com.qf.student.entity.Student;
import com.qf.student.service.IStudentService;
import com.qf.student.service.impl.StudentServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @version1.0
 * @auth dmh
 */

@WebServlet(urlPatterns = "/Student")
public class StudentController extends HttpServlet {

    private IStudentService studentService = new StudentServiceImpl();

    public StudentController(){

    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 1.判断获取action
        String action = req.getParameter("action");

        // 2.根据action来调用不同的方法
        if ("add".equals(action)) {
            // 执行添加操作
            addStudent(req,resp);
        }else if ("del".equals(action)) {
            del(req,resp);
        }  else if ("update".equals(action)) {
            update(req,resp);
        } else if ("byId".equals(action)) {
            byId(req,resp);
        } else if ("list".equals(action)) {
            list(req,resp);
        }else if("checkName".equals(action)){
            checkName(req,resp);
        }
    }

    private void checkName(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //1.获取需要检查的名称
        String name = req.getParameter("name");
        //2.根据名称查询一次
        Student student = studentService.getByName(name);

        //准备一个Map
        Map<String,Object> map=new HashMap<>();

        if(student!=null){
            //把要返回给前端的数据全部封装到一个Map中
            map.put("code",100);//存在或者不存在
            map.put("msg","["+name+"] 已存在");
        }else{
            map.put("code",200);//存在或者不存在
            map.put("msg","["+name+"] 不存在");
        }
        //吧Map封装成JSON字符串
        String jsonString = JSON.toJSONString(map);

        //写给前端的还一个JSON
        resp.getWriter().write(jsonString);

    }

    private void del(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //1.获取数据
        String id = req.getParameter("id");

        //类型转换
        int id2 = Integer.parseInt(id);
        //删除
        boolean remove = studentService.remove(id2);
        //判断
        if(remove){
            //删除成功回到查询列表
            resp.sendRedirect("/Student?action=list");

        }else{
            resp.getWriter().write("删除失败!");
        }
    }

    private void list(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException {
        //1.查询数据
        List<Student> list = studentService.list();

        //2.把数据放到作用域中
        req.setAttribute("studentList",list);


        //3.转发到视图转发
        req.getRequestDispatcher("studentList.jsp").forward(req,resp);

    }

    private void byId(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException {

        //获取传递过来的id
        String id2 = req.getParameter("id");

        //根据id查询学生信息
        Student student = studentService.getById(Integer.parseInt(id2));

        //将学生对象方进域对象里面,将爱好对象用,号隔开的方式转换成字符串放进域对象里面
        StringBuffer stringBuffer=new StringBuffer();
        List<String> loves = student.getLoves();
        for (String love : loves) {
            stringBuffer.append(love).append(",");
        }
        req.setAttribute("loves",stringBuffer.toString());
        req.setAttribute("student",student);

        //跳转更新页面
        req.getRequestDispatcher("updateStudent.jsp").forward(req,resp);

    }

    private void update(HttpServletRequest req,HttpServletResponse resp) throws IOException {
        // 1、更新肯定会有参数的，所以需要获取参数
        String name = req.getParameter("name");
        String age = req.getParameter("age");
        String sex = req.getParameter("sex"); // 用户输入男和女
        String email = req.getParameter("email");
        String phone = req.getParameter("phone");
        String id = req.getParameter("id");
        String loves = req.getParameter("loves");
        String course = req.getParameter("course");


        // 2、封装到成一个对象
        Student student = new Student();
        student.setId(Integer.parseInt(id));
        student.setName(name);
        // 把String类型转成int类型
        student.setAge(Integer.parseInt(age)); // 类型转换了==》从request对象中获取到的数据都是String类型
        student.setEmail(email);
        student.setPhone(phone);
        student.setSex(Integer.valueOf(sex));
        //把数组转成集合
        student.setLoves(Arrays.asList(loves));
        student.setCourse(course);
        // 3.调用业务层修改学生数据
        boolean update = studentService.update(student);
        if(update){
            //更新成功就跳转页面到列表(用重定向)
            resp.sendRedirect("Student?action=list");
        }else{
            resp.getWriter().write("更新失败");
        }

    }

    private Student studentById(HttpServletRequest req) {
            String id = req.getParameter("id");
            return studentService.getById(Integer.parseInt(id));
        }


    private void addStudent(HttpServletRequest req,HttpServletResponse resp) throws IOException {

        // 1、添加肯定会有参数的，所以需要获取参数
        String name = req.getParameter("name");
        String age = req.getParameter("age");
        String sex = req.getParameter("sex"); // 用户输入男和女
        String email = req.getParameter("email");
        String phone = req.getParameter("phone");
        String[] loves = req.getParameterValues("loves");
        String course = req.getParameter("course");

        // 2、封装到成一个对象
        Student student = new Student();
        student.setName(name);
        // 把String类型转成int类型
        student.setAge(Integer.parseInt(age)); // 类型转换了==》从request对象中获取到的数据都是String类型
        student.setEmail(email);
        student.setPhone(phone);
        student.setSex(Integer.valueOf(sex));
        //把数组转成集合
        student.setLoves(Arrays.asList(loves));
        student.setCourse(course);

        // 3.调用业务层添加学生
        boolean save = studentService.save(student);
        // 根据添加的结果响应用户
        if (save) {
            //如果添加成功了就展示页面给用户看,跳转到列表页面
//                resp.getWriter().write("添加成功");
            resp.sendRedirect("Student?action=list");//重定向是两次请求
        } else {
            resp.getWriter().write("添加失败");
        }
    }
}